package cn.tedu.eb_film.service.impl;

import cn.tedu.eb_film.ex.ServiceException;
import cn.tedu.eb_film.mapper.*;
import cn.tedu.eb_film.pojo.dto.CinemaAddNewDTO;
import cn.tedu.eb_film.pojo.dto.CinemaFormDTO;
import cn.tedu.eb_film.pojo.dto.CinemaUpdateDTO;
import cn.tedu.eb_film.pojo.dto.ServiceCinemaUpdateDto;
import cn.tedu.eb_film.pojo.entity.Cinema;
import cn.tedu.eb_film.pojo.entity.ServiceCinema;
import cn.tedu.eb_film.pojo.vo.*;
import cn.tedu.eb_film.pojo.entity.CinemaList;
import cn.tedu.eb_film.service.CinemaService;
import cn.tedu.eb_film.utils.ServiceCode;
import cn.tedu.eb_film.utils.StateCode;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.tedu.eb_film.pojo.page.CinemaPagination;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 电影院服务实现类
 *
 * @author ライナー・ロンテ
 * @since 2023/3/14 19:37
 */
@Slf4j
@Service
public class CinemaServiceImpl implements CinemaService {
    @Autowired
    private CinemaMapper cinemaMapper;
    @Autowired
    private ServiceCinemaMapper serviceCinemaMapper;
    @Autowired
    private CsChangeRegulationMapper csChangeRegulationMapper;
    @Autowired
    private CsChildPreferenceMapper csChildPreferenceMapper;
    @Autowired
    private CsParkingRateMapper csParkingRateMapper;
    @Autowired
    private CsRevocationRegulationMapper csRevocationRegulationMapper;
    @Autowired
    private CsTDCSMapper csTDCSMapper;

    @Override
    public void addNew(CinemaFormDTO cinemaFormDTO) {
        log.debug("开始处理电影院新增");
        final CinemaStandardVO cinemaStandardVO = cinemaMapper.getStandardVOByAddress(cinemaFormDTO.getAddress());
        if (cinemaStandardVO != null) {
            String message = "新增失败,该地址电影院已经存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        ServiceCinema serviceCinema = new ServiceCinema();

        serviceCinema.setChangeRegulationId(cinemaFormDTO.getChangeRegulation());
        serviceCinema.setChildPreferenceId(cinemaFormDTO.getChildPreference());
        serviceCinema.setParkingRateId(cinemaFormDTO.getParkRate());
        serviceCinema.setRevocationRegulationId(cinemaFormDTO.getRevRegulation());
        serviceCinema.setThreeDimensionsChargingStandardId(cinemaFormDTO.getThereDim());
        serviceCinema.setCreateTime(LocalDateTime.now());
        serviceCinema.setUpdateTime(LocalDateTime.now());
        serviceCinema.setState(1);

        serviceCinemaMapper.AddCinemaService(serviceCinema);
        System.out.println(serviceCinema.getId());

        Cinema cinema = new Cinema();
        cinema.setName(cinemaFormDTO.getName());
        cinema.setAddress(cinemaFormDTO.getAddress());
        cinema.setCreateTime(LocalDateTime.now());
        cinema.setUpdateTime(LocalDateTime.now());
        cinema.setServiceId(serviceCinema.getId());
        cinema.setState(0);

        final int rows = cinemaMapper.insert(cinema);
        if (rows != 1) {
            String message = "新增失败,新增电影院数据不为1";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
        log.debug("新增完成");
    }

    @Override
    public void addNews(List<CinemaAddNewDTO> cinemaAddNewDTOS) {
        log.debug("开始批量处理处理电影院新增");

        cinemaAddNewDTOS.forEach(addNew -> {
            CinemaStandardVO standardVO = cinemaMapper.getStandardVOByAddress(addNew.getAddress());
            if (standardVO != null) {
                String message = "新增失败,该地址电影院已经存在";
                log.warn(message + "电影院为{}", addNew);
                throw new ServiceException(ServiceCode.ERROR_INSERT, message);
            }
        });

        List<Cinema> cinemas = new ArrayList<>();
        cinemaAddNewDTOS.forEach(addNew -> {
            Cinema cinema = new Cinema();
            BeanUtils.copyProperties(addNew, cinema);
            cinema.setCreateTime(LocalDateTime.now());
            cinema.setCreateTime(LocalDateTime.now());
            cinemas.add(cinema);
        });
        log.debug("开始插入到数据库");
        int rows = cinemaMapper.inserts(cinemas);
        if (rows <= 1) {
            String message = "新增失败,新增电影院数据不大于1";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
        log.debug("新增完成");
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始根据id删除电影院数据");
        final CinemaStandardVO standardVO = cinemaMapper.getStandardVOById(id);
        if (standardVO == null || StateCode.STATE_DELETE.getValue().equals(standardVO.getState())) {
            String message = "删除失败,该地址电影院不存在存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }

        final int rows = cinemaMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除失败,该地址电影院数据不为1";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
        log.debug("删除成功");
    }

    @Override
    public void deleteByIds(List<Long> id) {
        log.debug("开始批量删除数据");
        id.forEach(item -> {
            final CinemaStandardVO standardVO = cinemaMapper.getStandardVOById(item);
            if (standardVO == null || StateCode.STATE_DELETE.getValue().equals(standardVO.getState())) {
                String message = "删除失败,该电影院不存在";
                log.warn(message + "电影院id为{}", item);
                throw new ServiceException(ServiceCode.ERROR_DELETE, message);
            }

        });

        List<Long> ids = new ArrayList<>(id);

        final int rows = cinemaMapper.deleteByIds(ids);
        if (rows <= 1) {
            String message = "删除失败,该电影院数据不大于1";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
        log.debug("删除成功");
    }

    @Override
    public Long count() {
        log.debug("开始统计总数量");
        return cinemaMapper.count();
    }

    @Override
    public CinemaStandardVO getCinemaStandardVOById(Long id) {
        log.debug("开始处理根据Id查询数据");
        final CinemaStandardVO standardVO = cinemaMapper.getStandardVOById(id);
        if (standardVO == null || StateCode.STATE_DELETE.getValue().equals(standardVO.getState())) {
            String message = "查询失败,该数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_SELECT, message);
        }
        return standardVO;
    }

    @Override
    public CinemaServiceVO getCinemaServiceVOById(Long id) {
        final CinemaStandardVO standard = cinemaMapper.getStandardVOById(id);
        if (standard == null || StateCode.STATE_DELETE.getValue().equals(standard.getState())) {
            String message = "获取失败,该电影院不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        CinemaServiceVO cinemaServiceVO = new CinemaServiceVO();
        ServiceCinemaVo service = serviceCinemaMapper.GetServiceCinemaById(standard.getServiceId());
        if (service == null || StateCode.STATE_DELETE.getValue().equals(service.getState())) {
            return cinemaServiceVO;
        }

        final CsChildPreferenceVo childPreference =
                csChildPreferenceMapper.getCsChildPreferenceById(service.getChildPreferenceId());
        if (childPreference == null || StateCode.STATE_DISABLE.getValue().equals(childPreference.getState())) {
            cinemaServiceVO.setChildPreferenceConnect(null);
        } else {
            cinemaServiceVO.setChildPreferenceConnect(childPreference.getConnect());
        }

        final CsChangeRegulationVo changeRegulation =
                csChangeRegulationMapper.getChangeRegulationById(service.getChangeRegulationId());
        if (changeRegulation == null || StateCode.STATE_DISABLE.getValue().equals(changeRegulation.getState())) {
            cinemaServiceVO.setChangeRegulationConnect(null);
        } else {
            cinemaServiceVO.setChangeRegulationConnect(changeRegulation.getConnect());
        }

        final CsTDCSStandardVO csTDCSStandard =
                csTDCSMapper.selectById(service.getThreeDimensionsChargingStandardId());
        System.out.println("csTDCSStandard = " + csTDCSStandard);
        if (csTDCSStandard == null || StateCode.STATE_DISABLE.getValue().equals(csTDCSStandard.getState())) {
            cinemaServiceVO.setThereDimChargingConnect(null);
        } else {
            cinemaServiceVO.setThereDimChargingConnect(csTDCSStandard.getPrice().toString());
        }

        final CsParkingRateStandardVO csParkingRate = csParkingRateMapper.selectById(service.getParkingRateId());
        if (csParkingRate == null || StateCode.STATE_DISABLE.getValue().equals(csParkingRate.getState())) {
            cinemaServiceVO.setParkRateConnect(null);
        } else {
            cinemaServiceVO.setParkRateConnect(csParkingRate.getConnect());
        }

        final CsRevocationRegulationStandardVO csRevocationRegulation =
                csRevocationRegulationMapper.getStandardById(service.getRevocationRegulationId());
        if (csRevocationRegulation == null || StateCode.STATE_DISABLE.getValue().equals(csRevocationRegulation.getState())) {
            cinemaServiceVO.setRevRegulationConnect(null);
        } else {
            cinemaServiceVO.setRevRegulationConnect(csRevocationRegulation.getConnect());
        }
        System.out.println(cinemaServiceVO);
        return cinemaServiceVO;
    }

    @Override
    public List<CinemaList> list() {
        log.debug("开始分页查询所有数据");
        return cinemaMapper.list();
    }

    @Override
    public CinemaListVO pageList(CinemaPagination pagination) {
        log.debug("开始处理分页查询所有数据");
        Integer page = pagination.getPagination().getPage() - 1;
        Integer pagesize = pagination.getPagination().getPagesize();
        String name = pagination.getName();
        String address = pagination.getAddress();

        final List<CinemaList> cinemaLists = cinemaMapper.pageList((page * pagesize), pagesize, name, address);
        final Long count = cinemaMapper.countForPage(name, address);

        CinemaListVO cinemaListVO = new CinemaListVO();

        cinemaListVO.setList(cinemaLists);
        cinemaListVO.setCount(count);

        return cinemaListVO;
    }

    @Override
    public void update(CinemaUpdateDTO cinemaUpdateDTO) {
        log.debug("开始修改编辑数据");
        final CinemaStandardVO standardVOById = cinemaMapper.getStandardVOById(cinemaUpdateDTO.getId());
        if (standardVOById == null || StateCode.STATE_DELETE.getValue().equals(standardVOById.getState())) {
            String message = "修改失败,改数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

        final CinemaStandardVO standard =
                cinemaMapper.getStandardVOByAddressAndName(cinemaUpdateDTO.getAddress(), cinemaUpdateDTO.getName());
        if (standard != null) {
            String message = "修改失败,已经占用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

        Cinema cinema = new Cinema();
        BeanUtils.copyProperties(cinemaUpdateDTO, cinema);
        cinema.setUpdateTime(LocalDateTime.now());

        final int rows = cinemaMapper.update(cinema);
        if (rows != 1) {
            String message = "修改失败,修改条数不为1";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
        log.debug("修改成功");
    }

    @Override
    public void enable(Long id) {
        updateEnable(id, StateCode.STATE_ENABLE);
    }

    @Override
    public void disable(Long id) {
        updateEnable(id, StateCode.STATE_DISABLE);
    }



    private void updateEnable(Long id, StateCode code) {
        log.warn("开始对id{},进行{}操作", id, ENABLE_TEXT[code.getValue()]);
        final CinemaStandardVO standard = cinemaMapper.getStandardVOById(id);
        if (standard == null || StateCode.STATE_DELETE.getValue().equals(standard.getState())) {
            String message = "修改失败,文件不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        if (standard.getState().equals(code.getValue())) {
            String message = "修改失败,文件已经是这个状态";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

        Cinema cinema = new Cinema();
        cinema.setId(id);
        cinema.setState(code.getValue());
        final int rows = cinemaMapper.update(cinema);
        if (rows != 1) {
            String message = "修改失败,修改文件数量不为1";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
        log.debug("{}完成", ENABLE_TEXT[code.getValue()]);
    }

    @Override
    public void edit(CinemaFormDTO cinemaFormDTO) {
        log.debug("开始处理编辑电影院");
        final CinemaStandardVO cinemaStandardVO = cinemaMapper.getStandardVOByAddress(cinemaFormDTO.getAddress());
        if (cinemaStandardVO == null) {
            String message = "编辑失败,该电影院不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

        ServiceCinemaUpdateDto serviceCinema = new ServiceCinemaUpdateDto();

        serviceCinema.setId(cinemaStandardVO.getServiceId());
        serviceCinema.setChangeRegulationId(cinemaFormDTO.getChangeRegulation());
        serviceCinema.setChildPreferenceId(cinemaFormDTO.getChildPreference());
        serviceCinema.setParkingRateId(cinemaFormDTO.getParkRate());
        serviceCinema.setRevocationRegulationId(cinemaFormDTO.getRevRegulation());
        serviceCinema.setThreeDimensionsChargingStandardId(cinemaFormDTO.getThereDim());
        serviceCinemaMapper.updateServiceCinema(serviceCinema);

        Cinema cinema = new Cinema();
        cinema.setName(cinemaFormDTO.getName());
        cinema.setAddress(cinemaFormDTO.getAddress());
        cinema.setState(0);
        cinema.setId(cinemaFormDTO.getId());

        final int rows = cinemaMapper.update(cinema);
        if (rows != 1) {
            String message = "修改失败,修改的数据不为1";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
        log.debug("新增完成");
    }

    @Override
    public List<SearchCinemaVo> getCinema(String name) {
        List<SearchCinemaVo> list = cinemaMapper.getCinema(name);
        log.info("参数{}",list);
        return list;
    }

    @Override
    public List<SearchCinemaVo> loadCinema() {
        List<SearchCinemaVo> list = cinemaMapper.loadCinema();
        return list;
    }

    @Override
    public List<SearchCinemaVo> getCinemaByAddress(String address) {
        List<SearchCinemaVo> list = cinemaMapper.getCinemaByAddress(address);
        return list;
    }

    @Override
    public List<SearchCinemaVo> Imax() {
        List<SearchCinemaVo> list = cinemaMapper.Imax();
        return list;
    }

    @Override
    public List<SearchCinemaVo> normal() {
        List<SearchCinemaVo> list = cinemaMapper.normal();
        return list;
    }
}
